from django.http import HttpResponseBadRequest, JsonResponse
import pickle, base64
from django_redis import get_redis_connection
def carts_merge(request, response):
    # 判断用户是否有cookie购物车
    user = request.user
    sku_cookie = request.COOKIES.get('carts')
    if sku_cookie is None:
        return HttpResponseBadRequest('没有数据')
    # 解密cookie
    sku_dict = pickle.loads(base64.b64decode(sku_cookie.encode()))

    # 读取cookie中的购物车数据
    selected_add_list = []
    selected_remove_list = []
    carts_dict = {}
    for sku_id in sku_dict.keys():
        if sku_dict[sku_id]['selected']:
            selected_add_list.append(sku_id)
        else:
            selected_remove_list.append(sku_id)
        carts_dict[sku_id] = sku_dict[sku_id]['count']


    # 将数据写入redis中
    redis_conn = get_redis_connection('carts')
    redis_conn.hmset('carts_%s' % user.id, carts_dict)

    if selected_add_list:
        redis_conn.sadd('selected_%s' % user.id, *selected_add_list)
    if selected_remove_list:
        redis_conn.srem('selected_%s' % user.id, *selected_remove_list)

    # 清除cookies
    response.delete_cookie('carts')


    return response
